# excel文件转TS文件
import shutil
import os
import xlrd
import logPrint
import zipfile

# 配置文件
configPath = os.getcwd() + "\config.txt"
configFile = open(configPath, "r", encoding="utf-8")
configContent = configFile.readlines()
# excel文件目录
excelPath = configContent[0].split("=")[1].strip('\n')
excelPath = os.path.abspath(os.path.join(os.getcwd(), excelPath))
# TS导出目录
TSPath = configContent[1].split("=")[1].strip('\n')
TSPath = os.path.abspath(os.path.join(os.getcwd(), TSPath))
# Json文件临时目录
JsonTemp = os.getcwd() + "\JsonTemp"
# bin文件导出目录
BinPath = configContent[2].split("=")[1].strip('\n')
# print(TSPath)

logPrint.logStart()

# excel文件转TS文件


def ExcelToTS():
    if (not os.path.exists(excelPath)):
        logPrint.logPrint("dir not exit")
        return
    if not os.path.exists(TSPath):
        os.makedirs(TSPath)
    if os.path.exists(JsonTemp):
        # 删除上次的缓存
        shutil.rmtree(JsonTemp)
    pass
    os.makedirs(JsonTemp)
    # 遍历excel文件
    for root, dirs, files in os.walk(excelPath):
        for d in files:
            handleExcel(os.path.join(root, d), TSPath)
    Compress(JsonTemp, "configs.bin", BinPath)

# 处理excel文件


def handleExcel(file, destSrc):
    logPrint.logPrint("excel file:" + file)
    excelFile = xlrd.open_workbook(file)
    # 解析excel文件
    for i in range(excelFile.nsheets):
        keyList = []
        noteList = []
        typeList = []
        sheetData = excelFile.sheets()[i]
        rowCnt = sheetData.nrows
        nameCN = sheetData.name
        rowName = sheetData.row_values(0)[0]  # 表名
        rowNote = sheetData.row_values(1)  # 注释
        rowKey = sheetData.row_values(2)  # 键名
        rowType = sheetData.row_values(3)  # 类型
        columnCnt = len(rowKey)
        for c in range(columnCnt):
            keyList.append(rowKey[c])
            noteList.append(rowNote[c])
            typeList.append(rowType[c])
        # 拼接excel文件内容
        logPrint.logPrint("转换TS文件:" + str(rowName) + "Cfg.ts")
        tsFlie = open(destSrc + "/" + rowName +
                      "Cfg.ts", "w", encoding="utf-8")
        content = ""
        content += ("/**\n * " + nameCN + "\n */\n")
        content += ("export interface " + rowName + "Cfg" + " {\n")
        for c in range(columnCnt):
            content += ("\t" + keyList[c]+": " +
                        typeList[c] + ", //" + noteList[c] + "\n")
        content += ("}\n")
        tsFlie.write(content)
        tsFlie.close()

        # 转为Json文件
        logPrint.logPrint("转换Json文件:" + str(rowName)+str(rowCnt) + ".json")
        jsonFlie = open(JsonTemp + "/" + rowName +
                        ".json", "w", encoding="utf-8")
        content = ""
        content += "{\n\t\"title\": [\n"
        for c in range(columnCnt):
            content += "\t\t\"" + keyList[c] + "\""
            if c != columnCnt - 1:
                content += ",\n"
            else:
                content += "\n"
        content += "\t],\n"
        content += "\t\"content\":[ \n"
        for c in range(rowCnt):
            if c >= 4:
                content += "\t\t[\n"
                data = sheetData.row_values(c)
                for i in range(columnCnt):
                    val = data[i]
                    if "number" != typeList[i]:
                        val = "\"" + str(val) + "\""
                    else:
                        if 0 == val % 1:
                            val = str(int(val))
                        else:
                            val = str(val)
                    if i == columnCnt - 1:
                        content += "\t\t\t" + val + "\n"
                        if c == rowCnt - 1:
                            content += "\t\t]\n"
                        else:
                            content += "\t\t],\n"
                    else:
                        content += "\t\t\t" + val + ",\n"
        content += "\t]\n}"

        jsonFlie.write(content)
        jsonFlie.close()


# 压缩


def Compress(dest, fileName, proDir):
    fileDest = dest + "/" + fileName
    logPrint.logPrint("compress start" + fileDest)
    zipf = zipfile.ZipFile(fileName, 'w', zipfile.ZIP_DEFLATED)
    for root, dirs, files in os.walk(JsonTemp):
        for file in files:
            filePath = os.path.join(root, file)
            logPrint.logPrint("compress - " + file)
            zipf.write(filePath, file)
    zipf.close()
    logPrint.logPrint(fileDest+"--to--" + proDir)
    shutil.copy(fileName, proDir)
    logPrint.logPrint("compress end")


ExcelToTS()

logPrint.logEnd()
